<template>
  <view class="docMainInfo">
    <view class="myNavFlexd">
      <view class="myNav">
        <AtNavBar
          :onClickLeftIcon="goBackClick"
          color="#000"
          :title="myTitle"
          leftIconType="chevron-left"
        />
        <view class="save" @tap="savePage" v-if="role === 'student'">保存</view>
      </view>
    </view>
    <view class="mySteps">
      <scroll-view :scrollX="true">
        <AtSteps
          :items="items"
          :current="currentPage-1"
        />
      </scroll-view>
    </view>

    <AtForm v-show="currentPage === 1">
      <AtInput
        :disabled="lock || !roleLock"
        name="dept_name"
        title="实习科室:"
        type="text"
        placeholder="请输入实习科室"
        :value="mainInfo.dept_name"
        :onChange="handleChange.bind(this,'dept_name')"
      />
      <view class="dateItem">
        <picker
          :disabled="lock || !roleLock"
          mode="date"
          v-model="mainInfo.operate_date"
        >
          <view class="demo-list-item">
            <view class="demo-list-item__label">汇报日期:</view>
            <view class="demo-list-item__value">{{ mainInfo.operate_date }}</view>
          </view>
        </picker>
      </view>
      <AtInput
        :disabled="lock || !roleLock"
        name="stu_name"
        title="实习生姓名:"
        type="text"
        placeholder="请输入实习生姓名"
        :value="mainInfo.stu_name"
        :onChange="handleChange.bind(this,'stu_name')"
      />
      <AtInput
        :disabled="lock || !roleLock"
        name="stu_num"
        title="实习生学号:"
        type="text"
        placeholder="请输入实习生学号"
        :value="mainInfo.stu_num"
        :onChange="handleChange.bind(this,'stu_num')"
      />
      <AtInput
        :disabled="lock || !roleLock"
        class="theme"
        name="theme"
        :title="mod_id === 'jkjy' ? '健康教育主题:' : mod_id === 'xjk' ? '小讲课:' : '读书报告主题:'"
        type="text"
        :placeholder="mod_id === 'jkjy' ? '请输入健康教育主题' : mod_id === 'xjk' ? '请输入小讲课主题' : '请输入读书报告主题'"
        :value="mainInfo.theme"
        :onChange="handleChange.bind(this,'theme')"
      />
      <view class="XS"
            v-if="mod_id === 'jkjy'"
      >
        健康教育形式:
      </view>
      <AtRadio

        v-if="mod_id === 'jkjy'"
        :options="radioOptions1"
        :value="radioValue1"
        :onClick="handleRadioChange"
      />
    </AtForm>
    <AtForm v-show="currentPage === 2">
      <view class="uploadPdf">
        <view class="title">{{ mod_id === "jkjy" ? "自我总结:" : mod_id === 'xjk' || "dsbg" ? "汇报用PPT:" : "" }}</view>
        <input
          :disabled="lock || !roleLock"
          class="myInput"
          type="file"
          @change="addFile"
          accept="application/pdf"
        >
        <view class="tips">(文件类型PDF)请转为PDF格式后上传。</view>
      </view>
      <AtButton type="primary" size="small" :onClick="submitDoc" v-if="role === 'student'">提交</AtButton>
    </AtForm>
    <AtForm v-show="currentPage === 3">
      <AtInput
        :disabled="lock || roleLock"
        name="t_name"
        title="带教老师姓名:"
        type="text"
        placeholder="请输入带教老师姓名"
        :value="mainInfo.t_name"
        :onChange="handleChange.bind(this,'t_name')"
      />

      <AtInput
        :disabled="lock || roleLock"
        name="t_title"
        title="带教老师职称:"
        type="text"
        placeholder="请输入带教老师职称"
        :value="mainInfo.t_title"
        :onChange="handleChange.bind(this,'t_title')"
      />
      <view class="myTextarea">
        <view class="XS"
        >
          带教评语:
        </view>
        <AtTextarea
          :disabled="lock || roleLock"
          class="mytextarea"
          name="remark"
          :value="mainInfo.remark"
          :onChange="handleChange.bind(this,'remark')"
          :maxLength="800"
          placeholder="带教评语"
        />
      </view>
      <view class="myImage">
        <view class="XSimg"
        >
          带教工作证:
        </view>
        <view class="img">
          <AtImagePicker
            :showAddBtn="imglock"
            :files="files"
            count="1"
            :onChange="onChange"
          />
        </view>
      </view>
    </AtForm>
    <view v-if="page === 3">
      <Sign title="带教老师签名" :role="lock || roleLock" @getSignUrl="getSignUrl"></Sign>
      <AtButton class="deptBtn" type="primary" size="small" :onClick="submitDocDept" v-if="role === 'dept'">提交
      </AtButton>
    </view>
    <view class="myPages">
      <AtPagination
        :total="3"
        :pageSize="1"
        :current="currentPage1"
        :onPageChange="onPageChange"
      >
      </AtPagination>
    </view>
    <AtMessage/>

  </view>
</template>

<script>

import './index.scss'
import Taro from "@tarojs/taro";
import Sign from "../../components/Sign";

export default {
  components: {Sign},
  data() {
    return {
      roleLock: false,
      role: '',
      token: "",
      files: [
        // {
        //   type: 'btn'
        // }
      ],
      myTitle: "",
      uploadUrl: "http://npis.mocoder.cn/?s=App.Doc_Student.Upload",
      imgUploadUrl: "http://npis.mocoder.cn/?s=App.Doc_Unit.Upload",
      pdfUrl: "",
      imageUrl: "",
      lock: false,
      items: [
        {title: '基本信息'},
        {title: '汇报内容'},
        {title: '带教审核'}
      ],
      currentPage: 1,
      currentPage1: 1,
      mod_id: "",
      doc_id: "",
      page: 1,
      mainInfo: {},
      radioValue1: 'option1',
    }
  },
  computed: {
    imglock() {
      if (this.lock) {
        return false
      }
      return !this.roleLock;

    },
    radioOptions1() {
      return [
        {label: '集体宣教', value: 'option1', disabled: this.lock || !this.roleLock},
        {label: '个别宣教', value: 'option2', disabled: this.lock || !this.roleLock},
        {label: '制作手册或画报', value: 'option3', disabled: this.lock || !this.roleLock},
        {label: '其他', value: 'option4', disabled: this.lock || !this.roleLock}
      ]
    },
  },
  created() {
    this.currentPage = Taro.getStorageSync("itemDocInfo").current_page;
    this.currentPage1 = Taro.getStorageSync("itemDocInfo").current_page;
    this.page = Taro.getStorageSync("itemDocInfo").current_page;
  },
  mounted() {
    this.doc_id = this.$taro.Current.router.params.doc_id;
    this.mod_id = this.$taro.Current.router.params.mod_id;
    this.myTitle = Taro.getStorageSync("itemDocInfo").title;
    this.role = Taro.getStorageSync("userInfo").role;
    this.token = Taro.getStorageSync("token")
    if (this.role === "student") {
      this.roleLock = true
    }
    if (this.role === 'student') {
      this.getDocStudent()
    } else {
      this.getDocDept()
    }
  },
  methods: {
    getSignUrl(e) {
      // console.log(e)
      let ImgObj = this.dataURLtoFile(e, 'img.png');
      let signImgUrl = this.getObjectURL(ImgObj);
      // console.log(ImgObj)
      // console.log(this.getObjectURL(ImgObj))
      // console.log(signImgUrl)
      Taro.uploadFile({
        url: this.imgUploadUrl,
        filePath: signImgUrl,
        header: {
          'Authorization': this.token
        },
        name: 'file',//修改上传文件的名称
        fileName: "file.png",
      }).then((res, rej) => {
        console.log(res, rej)
        let tempData = JSON.parse(res.data)
        if (tempData.ret === 200) {
          this.mainInfo.t_sign = tempData.data.url
          Taro.atMessage({
            message: '上传签名成功',
            type: 'success'
          })
        } else {
          Taro.atMessage({
            message: '上传签名失败',
            type: 'warning'
          })
        }
      })
    },
    // 获取上传图片文件的真实路径
    getObjectURL(file) {
      var url = null;
      if (window.createObjcectURL !== undefined) {
        url = window.createOjcectURL(file);
      } else if (window.URL !== undefined) {
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL !== undefined) {
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },
    // 将base64转换为文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var bytes = window.atob(arr[1]);            // 去掉url的头，并转化为byte
      //let n = new ArrayBuffer(bytes.length);    // 处理异常,将ascii码小于0的转换为大于0
      var n = bytes.length,
        u8arr = new Uint8Array(n);                  // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
      while (n--) {
        u8arr[n] = bytes.charCodeAt(n);
      }
      return new File([u8arr], filename, {type: mime});
    },
    submitDocDept() {
      this.submitDeptDoc();
    },
    submitDoc(e) {
      this.submitStuDoc();
    },
    onChange(files) {
      // console.log('chacha20')
      // console.log(files)
      if (files.length === 1) {
        //   files.splice(0,1);
        //   console.log(files)
        this.files = files
        Taro.uploadFile({
          url: this.imgUploadUrl,
          filePath: files[0].file.path,
          header: {
            'Authorization': this.token
          },
          name: 'file',//修改上传文件的名称
          fileName: "file.png",
        }).then((res, rej) => {
          console.log(res, rej)
          let tempData = JSON.parse(res.data)
          this.mainInfo.t_photo = tempData.data.url
          this.mainInfo.t_sign = 'http://npis.mocoder.cn/?s=App.Doc_Student.Upload'
          // console.log(this.mainInfo)
        })
      }

      if (files.length > 1) {
        files.splice(0, files.length - 1);
        this.files = files
      } else {
        this.files = files
      }
    },
    addFile(e) {
      console.log(e)
      if (e.target.children[0].files.length !== 0) {
        let resource = URL.createObjectURL(e.target.children[0].files[0])
        // console.log(resource)
        Taro.uploadFile({
          url: this.uploadUrl,
          filePath: resource,
          name: "file",
          fileName: 'file.pdf',
          header: {
            "Authorization": this.token
          }
        }).then((res, rej) => {
          console.log(res, rej)
          let data = JSON.parse(res.data)
          if (rej) {
            Taro.showToast({
              title: "文件上传失败",
              icon: "none"
            })
          }
          if (data.ret === 200) {
            this.pdfUrl = data.data.url;
            this.mainInfo.file = this.pdfUrl;
            console.log(this.pdfUrl)
          } else {
            Taro.showToast({
              title: "文件上传失败",
              icon: "none"
            })
          }
        })
      }
    },
    savePage() {
      if (this.page === 1) {
        this.radioOptions1.forEach((el, index) => {
          if (el.value === this.radioValue1) {
            this.mainInfo.form = el.label
          }
        })
      }
      // console.log(this.mainInfo);
      // console.log(JSON.stringify(this.mainInfo))
      this.updateDoc();
    },
    goBackClick() {
      Taro.navigateBack({
        delta: 1
      })
    },
    onPageChange(val) {
      // console.log(val)
      this.currentPage = val.current
      this.page = this.currentPage;
      //调整步骤条位置
      const scroll_position = [0, 0, 165, 340];
      this.$el.children[1].children[0].scrollLeft = scroll_position[this.currentPage];
      if (this.role === 'student') {
        this.getDocStudent()
      } else {
        this.getDocDept()
      }
      // console.log(this.currentPage)
    },
    handleRadioChange(value) {
      this.radioValue1 = value
      // console.log(this.radioValue1)
      //
      // console.log( this.mainInfo.form)
    },
    handleChange(name, val) {
      this.mainInfo[name] = val;
    },
    getDate() {
      let D = new Date();
      let year = D.getFullYear();
      let m = D.getMonth() + 1;
      if (m < 10) {
        m = '0' + m;
      }
      let d = D.getDate();
      if (d < 10) {
        d = '0' + d;
      }
      // console.log(year+'-'+m+'-'+d);
      return year + '-' + m + '-' + d
    },
    /**
     * 获取文档数据
     * @returns {Promise<void>}
     */
    async getDocStudent() {
      let res = await this.$myRequest({
        url: "?s=App.Doc_Student.GetDoc",
        data: {
          doc_id: this.doc_id,
          page: this.page
        }
      })
      // console.log(res)
      this.mainInfo = res.data.data.content;
      if (!this.mainInfo.operate_date) {
        this.mainInfo.operate_date = this.getDate();
      }
      if (res.data.data.locked === 1) {
        this.lock = true;
      }
    },
    /**
     * 获取文档数据
     * @returns {Promise<void>}
     */
    async getDocDept() {
      let res = await this.$myRequest({
        url: "?s=App.Doc_Unit.GetDoc",
        data: {
          doc_id: this.doc_id,
          page: this.page
        }
      })
      // console.log(res)
      this.mainInfo = res.data.data.content;
      if (res.data.data.locked === 1) {
        // console.log(res.data.data.locked)
        this.lock = true;
      } else {
        this.lock = false;
      }
      // console.log(this.lock)
    },
    /**
     *  更新文档数据
     * @returns {Promise<void>}
     */
    async updateDoc() {
      // console.log(this.mainInfo)
      let res = await this.$myRequest({
        url: "?s=App.Doc_Student.Update",
        data: {
          doc_id: this.doc_id,
          content: JSON.stringify(this.mainInfo),
          page: this.page
        }
      })
      console.log(res)
      if (res.data.ret === 200) {
        Taro.atMessage({
          message: '保存成功',
          type: "success"
        })
      }
    },
    /**
     * 提交文档审核
     * @returns {Promise<void>}
     */
    async submitStuDoc() {
      let res = await this.$myRequest({
        url: "?s=App.Doc_Student.Submit",
        data: {
          doc_id: this.doc_id,
        }
      })
      // console.log(res)
      if (res.data.ret === 200) {
        Taro.atMessage({
          message: "提交审核成功",
          type: "success"
        })
      }
    },
    /**
     * 带教提交文档审核
     * @returns {Promise<void>}
     */
    async submitDeptDoc() {
      let res = await this.$myRequest({
        url: "?s=App.Doc_Unit.Submit",
        data: {
          doc_id: this.doc_id,
          content: JSON.stringify(this.mainInfo),
          page: this.page
        }
      })
      // console.log(res)
      if (res.data.ret === 200) {
        this.files = []
        this.mainInfo = {}
        Taro.atMessage({
          message: "提交审核成功",
          type: "success"
        })
        await this.getDocDept()
      }
    },
  },
}
</script>

<style lang="less">
.deptBtn {
  margin-top: 1rem;
}

.myImage {
  display: flex;
  flex-direction: column;
  padding-left: 0.4rem;

  .XSimg {
    width: 7.3rem;
    font-size: 0.8rem;
    line-height: 1.5;
    vertical-align: middle;
    text-align: left;
    margin-left: 0.45rem;
    color: #333;
  }

  .img {
    margin-left: 0.7rem;
  }
}

.uploadPdf {
  display: flex;
  flex-direction: column;
  padding: 0px 1.5rem 0px 1.3rem;

  .weui-input {
    height: 2rem;
    margin-top: 9px;
  }

  .title {
    margin-right: 0.4rem;
    width: 7.3rem;
    font-size: 0.8rem;
    line-height: 1.5;
    vertical-align: middle;
    text-align: left;
    color: #333;
  }

  .tips {
    width: 100%;
    font-size: 0.75rem;
    line-height: 1.5;
    vertical-align: middle;
    text-align: left;
    color: #333;
  }
}

.myTextarea {
  .XS {
    margin-right: 0.4rem;
    width: 7.3rem;
    font-size: 0.8rem;
    line-height: 1.5;
    vertical-align: middle;
    text-align: left;
    margin-left: 0.75rem;
    color: #333;
  }

  .mytextarea {
    width: 80%;
    margin-left: 1.675rem;
    margin-top: 0.4rem;
  }
}

.docMainInfo {
  margin-bottom: 1.5rem;
}

.at-steps {
  width: 700PX;
}

.mySteps {
  margin-top: 3rem;
}

.myPages {
  position: fixed;
  width: 100%;
  bottom: 0px;
  background-color: #FFFFFF;
}

.myNavFlexd {
  position: fixed;
  top: 0px;
  width: 100%;
  background-color: #FFFFFF;
  z-index: 10;

  .myNav {
    margin-bottom: 20px;
    position: relative;

    .save {
      position: absolute;
      top: 0.39rem;
      right: 0.5rem;
      color: #333;
      font-size: 18PX;
    }
  }
}

.dateItem {
  display: flex;

  .demo-list-item__label, .demo-list-item__value {
    font-size: 0.8rem;
    line-height: 1.5;
    margin-right: 1rem;
    margin-left: 0.3rem;
  }
}

.XS {
  margin-right: 0.4rem;
  width: 7.3rem;
  font-size: 0.8rem;
  line-height: 1.5;
  vertical-align: middle;
  text-align: left;
  margin-left: 0.75rem;
  color: #333;
}

.theme {
  .at-input__title {
    width: 5.8rem;
  }
}

.at-input__title {
  width: 5.3rem;
}
</style>
